package com.ioidea.holland.jkListAct

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import cn.com.heaton.blelibrary.ble.BleRssiDevice
import cn.com.heaton.blelibrary.ble.callback.BleScanCallback
import cn.com.heaton.blelibrary.ble.model.ScanRecord
import com.ioidea.base.util.MyLogger
import com.ioidea.ble.bean.BleRequest
import com.ioidea.ble.bean.JkqMqttInfo
import com.ioidea.ble.proto.ProtoBase
import com.ioidea.ble.proto.ProtoGetConfig
import com.ioidea.holland.commonBle.CommonBleViewModel
import java.nio.charset.StandardCharsets

class JkListViewModel(private val jkListRes: JkListRes = JkListRes()) :
    CommonBleViewModel() {

    //蓝牙设备监听
    val liveDataScanBleRssiDevice = MutableLiveData<BleRssiDevice>()


    //jkqMqttInfo信息监听
    val liveDataJkqMqttInfoNotify = MutableLiveData<JkqMqttInfo>()

    //设置mqtt信息 成功失败
    val liveDataSetJkqMqttInfoNotify = MutableLiveData<Boolean>()

    //协议的解析
    val getConfigProto=ProtoGetConfig()
    //解析判断成功失败用
    var sn= ProtoBase.EMPTY_SN



    fun scan(adapterDatas: MutableList<BleRssiDevice>) {
        addTimeout()
        jkListRes.scan(object : BleScanCallback<BleRssiDevice>() {
            override fun onLeScan(device: BleRssiDevice, rssi: Int, scanRecord: ByteArray) {
                MyLogger.hLog().i("名字:  " + device.bleName)
                MyLogger.hLog().i("地址:  " + device.bleAddress)
                if (!TextUtils.isEmpty(device.bleName) && device.bleName.
                      startsWith(ProtoBase.SMART_PLC_NAME_START)
                ) {
                    //统一把sn处理好
                    device.sn =  getSn(device)
                    device.rssi = rssi
                    device.scanRecord = ScanRecord.parseFromBytes(scanRecord)
                    clearRepeat(adapterDatas,device)
                }
            }
        })
    }

    /**
     * 广播去重设备
     */
    private fun clearRepeat(data: MutableList<BleRssiDevice>,newSearchBle: BleRssiDevice): Int {
        //没找到
        var noFound = -1
        for (i in data.indices) {
            val bleRssiDevice = data[i]
            if (bleRssiDevice.bleAddress.equals(newSearchBle.bleAddress)) {
//                data[i]=newSearchBle
                noFound = i
                break
            }
        }
        //没找到 加是新的数据 加到集合里面 刷新UI
        if (noFound == -1 || data.isEmpty()) {
            liveDataScanBleRssiDevice.value = newSearchBle
            removeTimeout()
        }
        return noFound
    }



    private fun getSn(device: BleRssiDevice):String {
        val bleNameArray = device.bleName.split(ProtoBase.SMART_PLC_NAME_START)
        if (bleNameArray.size > 1) {
            return bleNameArray[1].trim()
        }
        return ""
    }

    fun connect(device: BleRssiDevice) {
        stopScan()
        addTimeout()
        jkListRes.connect(device)
    }

    fun stopScan() {
        jkListRes.stopScan()
    }


    fun getConnectDevice(): BleRssiDevice? {
      return  jkListRes.getConnectDevice()
    }


    fun testGetJkqMqttInfo(sn:String) {
        this.sn=sn
       val command= getConfigProto.getConfigCommand(sn)
        jkListRes.putRequest(BleRequest(command.toByteArray(StandardCharsets.US_ASCII)){
                bleResponse ->

            val jkqMqttInfo= getConfigProto.parseConfig(sn,bleResponse.responseDataArray.toString(StandardCharsets.US_ASCII))
            if (jkqMqttInfo!=null){
                liveDataJkqMqttInfoNotify.postValue(jkqMqttInfo!!)
            }
        })
    }



    fun testWriteJkqMqttInfo(writeData:String) {
        jkListRes.putRequest(BleRequest(writeData.toByteArray(StandardCharsets.US_ASCII)){
                bleResponse ->

            //这里可以使用protocol 处理解析 解析成对象
            MyLogger.hLog().e("data:$bleResponse")
            liveDataSetJkqMqttInfoNotify.postValue(true)
        })
    }






}